#include "uicontrol.h"

#include <QObject>
#include <QDebug>
#include <QString>
#include <QFile>
#include <QCoreApplication>
#include <QDir>


static QString FILE_DOORNO;
static QString FILE_QRCODE;
static QString Pic_Dir;
static QString File_INTERVAL;

UiControl::UiControl(QObject *parent) : QObject(parent)
{
    QString asset_dir = "ui";
    QString abs_dir_path=QCoreApplication::applicationDirPath() +QDir::separator()+asset_dir+QDir::separator();
    FILE_DOORNO=abs_dir_path+"doorNo.txt";
    FILE_QRCODE=abs_dir_path+"qr.jpg";
    Pic_Dir=abs_dir_path+"pic";
    File_INTERVAL=abs_dir_path+"interval.txt";

    sock_server=new SocketServer("ui.sock");
    connect(sock_server,SIGNAL(DoorNoChanged()),this,SLOT(onDoorNoChanged()));
    connect(sock_server,SIGNAL(PicChanged()),this,SLOT(onPicChanged()));
    connect(sock_server,SIGNAL(QrCodeChanged()),this,SLOT(onQrCodeChanged()));
    connect(sock_server,SIGNAL(IntervalChanged()),this,SLOT(onIntervalChanged()));
    qDebug()<<sock_server->startListen();
}

UiControl::~UiControl(){
    sock_server->close();
    delete sock_server;
}

void UiControl::initUI(){
    if (QFile::exists(FILE_DOORNO)){
        onDoorNoChanged();
    }
    if(QFile::exists(FILE_QRCODE)){
        onQrCodeChanged();
    }
    if(QDir(Pic_Dir).exists()){
        onPicChanged();
    }
    onIntervalChanged();
}


void UiControl::onDoorNoChanged(){
    qDebug()<<"doorNo change";
    QString strDoorNo = readFile(FILE_DOORNO);
    if(strDoorNo!=nullptr){
        qDebug()<<"update doorNo:"<<strDoorNo;
    } else {
        qDebug()<<"doorNo clear";
    }
    setDoorNo(strDoorNo);
}

void UiControl::onPicChanged(){
    qDebug()<<"pic change";
    QDir dir(Pic_Dir);
    if (!dir.exists()){
        qDebug()<<"pic dir not exist";
        return;
    }
    dir.setFilter(QDir::Files);
    dir.setSorting(QDir::Name);
    QFileInfoList files= dir.entryInfoList();
    QString filePaths;
    for (int i=0;i<files.size();i++) {
        filePaths+="file://"+files.at(i).absoluteFilePath()+",";
    }
    emit PicRewrite(filePaths.left(filePaths.size()-1));
}

void UiControl::onQrCodeChanged(){
    qDebug()<<"qrcode change";
    emit QrcodeRewrite("file://"+FILE_QRCODE);
}

void UiControl::onIntervalChanged(){
    qDebug()<<"interval change";
    QString interval = readFile(File_INTERVAL);
    if(interval!=nullptr){
        qDebug()<<"update interval:"<<interval;
    } else {
        qDebug()<<"interval reset default 10s";
        interval="10";
    }
    bool ok;
    int result = interval.toInt(&ok,10);
    if(ok){
        setInterval(result);
    }
}

QString UiControl::readFile(const QString &path){
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug()<<"Can't open file:"<<path<<endl;
        return nullptr;
    }
    QString str;
    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        str.append(QString(line));
    }
    file.close();
    return str;
}
